package com.ruoyi.develop.finance.financeInvoiceReceipt.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.finance.financeAr.service.IFinanceArService;
import com.ruoyi.develop.goodsInvoice.domain.GoodsInvoice;
import com.ruoyi.develop.goodsInvoice.service.IGoodsInvoiceService;
import com.ruoyi.develop.goodsInvoiceDetail.domain.GoodsInvoiceDetail;
import com.ruoyi.develop.goodsInvoiceDetail.service.IGoodsInvoiceDetailService;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.finance.financeInvoiceReceipt.domain.FinanceInvoiceReceipt;
import com.ruoyi.develop.finance.financeInvoiceReceipt.service.IFinanceInvoiceReceiptService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 客户回款单Controller
 * @author lmm
 * @date 2025-08-09
 */
@RestController
@RequestMapping("/financeInvoiceReceipt/financeInvoiceReceipt")
public class FinanceInvoiceReceiptController extends BaseController {
    @Autowired
    private IFinanceInvoiceReceiptService financeInvoiceReceiptService;
    @Autowired
    private IGoodsInvoiceService goodsInvoiceService;
    @Autowired
    private IGoodsInvoiceDetailService goodsInvoiceDetailService;
    @Autowired
    private IFinanceArService financeArService;
    @Autowired
    private IProjectBaseInfoService projectBaseInfoService;



    /**
     * 查询客户回款单列表
     */
    @PreAuthorize("@ss.hasPermi('develop:FinanceInvoiceReceipt:query')")
    @GetMapping("/list")
    public TableDataInfo list(FinanceInvoiceReceipt entity) {
        startPage();
        List<FinanceInvoiceReceipt> list = financeInvoiceReceiptService.selectList(entity);
        return getDataTable(list);
    }

    /**
     * 导出客户回款单列表
     */
    @PreAuthorize("@ss.hasPermi('develop:FinanceInvoiceReceipt:export')")
    @Log(title = "客户回款单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FinanceInvoiceReceipt entity) {
        List<FinanceInvoiceReceipt> list = financeInvoiceReceiptService.selectList(entity);
        ExcelUtil<FinanceInvoiceReceipt> util = new ExcelUtil<FinanceInvoiceReceipt>(FinanceInvoiceReceipt. class);
        util.exportExcel(response, list, "客户回款单数据");
    }


    /**
     * 导入客户回款单列表
     */
    @Log(title = "导入客户回款单列表", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(FinanceInvoiceReceipt entity, MultipartFile file) {
        Map<String, Object> resMap = new HashMap<>();
        resMap = financeInvoiceReceiptService.importData(entity,file);
        resMap.put("code", 200);
        return AjaxResult.success(resMap);
    }


    /**
     * 获取客户回款单详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:FinanceInvoiceReceipt:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(financeInvoiceReceiptService.selectById(id));
    }

    /**
     * 新增客户回款单
     */
    @PreAuthorize("@ss.hasPermi('develop:FinanceInvoiceReceipt:add')")
    @Log(title = "客户回款单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody FinanceInvoiceReceipt entity) {
        return toAjax(financeInvoiceReceiptService.insert(entity));
    }

    /**
     * 修改客户回款单
     */
    @PreAuthorize("@ss.hasPermi('develop:FinanceInvoiceReceipt:edit')")
    @Log(title = "客户回款单", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody FinanceInvoiceReceipt entity) {
        return toAjax(financeInvoiceReceiptService.update(entity));
    }

    /**
     * 删除客户回款单
     */
    @PreAuthorize("@ss.hasPermi('develop:FinanceInvoiceReceipt:remove')")
    @Log(title = "客户回款单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(financeInvoiceReceiptService.deleteByIds(ids));
    }



    /**
     * 核销订单
     */
    @PreAuthorize("@ss.hasPermi('develop:FinanceInvoiceReceipt:query')")
    @Transactional
    @GetMapping(value = "/writeOff")
    public AjaxResult writeOff(FinanceInvoiceReceipt entity) {
        if(StringUtils.isBlank(entity.getInvoiceId())){
            return AjaxResult.error("请选择发票");
        }
        if(StringUtils.isBlank(entity.getId())){
            return AjaxResult.error("请选择回款单");
        }

        FinanceInvoiceReceipt receipt =  financeInvoiceReceiptService.selectById(entity.getId());
        receipt.setInvoiceId(entity.getInvoiceId());
        receipt.setStatus(BusinessConstants.INVOICE_RECEIPT_STATUS_SUCCESS);
        receipt.setWay(BusinessConstants.INVOICE_RECEIPT_WAY_HAND);
        financeInvoiceReceiptService.update(receipt);
        // 插入核销记录
        GoodsInvoice goodsInvoice =  goodsInvoiceService.selectById(entity.getInvoiceId());
        goodsInvoice.setPinMoney(goodsInvoice.getPinMoney().add(receipt.getMoney()));
        goodsInvoice.setPinRemain(goodsInvoice.getPinRemain().subtract(receipt.getMoney()));
        // 判断是否核销完成
        if (goodsInvoice.getPinMoney().compareTo(goodsInvoice.getAmount()) == 0) {
            goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
        }
        if(goodsInvoice.getPinMoney().compareTo(goodsInvoice.getAmount()) < 0){
            goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
        }
        goodsInvoiceService.update(goodsInvoice);
        GoodsInvoiceDetail invoiceDetail = new GoodsInvoiceDetail();
        invoiceDetail.setInvoiceId(receipt.getInvoiceId());
        invoiceDetail.setCustomerId(goodsInvoice.getCustomerId());
        invoiceDetail.setPinDate(new Date());
        invoiceDetail.setPinMoney(receipt.getMoney());
        invoiceDetail.setCustomerName(goodsInvoice.getCustomerName());
        invoiceDetail.setProjectNo(goodsInvoice.getProjectNo());
        invoiceDetail.setProjectId(goodsInvoice.getProjectId());
        goodsInvoiceDetailService.insert(invoiceDetail);
        // 核销之后 生成应收 回款
        financeArService.addByBackMoney(invoiceDetail);

        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(goodsInvoice.getProjectId());
        if (projectBaseInfo != null) {
            projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().add(goodsInvoice.getPinMoney()));
            projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().subtract(goodsInvoice.getPinMoney()));
            if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
                projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                projectBaseInfo.setEndDate(new Date());
            }

            if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
            }
            if (projectBaseInfo.getRemainMoney().compareTo(projectBaseInfo.getContractMoney()) == 0) {
                projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
            }
            projectBaseInfoService.updateBackMoney(projectBaseInfo);
        }
        return AjaxResult.success();
    }




}
